-- Desc: 调拨订单减少锁定库存

local params = {}
local skuStockKeys = {}
local totalSkuStockKeys = {}

-- 将入参KEYS([订单id_仓库id_skuId_lockNum, ...])封装为params二元数组([[订单id, 仓库id, skuId, lockNum], ...])
-- 并获取对应sku区域库存key和sku总库存key
for index, paramStr in ipairs(KEYS) do
    -- 将paramStr解析成param数组
    local param = {}
    for value in string.gmatch(paramStr, "%d+") do
        table.insert(param, value)
    end
    table.insert(params, param)
    -- 获取sku区域库存key
    table.insert(skuStockKeys, "mall4j_product:sku_sock:"..param[3].."_"..param[2])
    table.insert(totalSkuStockKeys, "mall4j_product:sku_sock:"..param[3])
end

-- 执行redis的mget指令，批量获取sku区域库存key和总库存key对应的value值（unpack是将数组变成可变长参数）
local valueStrArr = redis.call('mget', unpack(skuStockKeys));
local totalValueStrArr = redis.call('mget', unpack(totalSkuStockKeys))

-- 删除库存锁定记录，并更新redis-sku库存数据(lua'..'相当于java'+')
-- 将新的key-value封装为数组，方便后续mset
-- 记录执行结果，用于返回(订单id_仓库id_skuId_可用库存)
local result = ""
local skuStockKV = {}
for i = 1, #params do
    -- 将valueStr和totalValueStr(可用数量_锁定数量_已售数量_状态)转成value数组([可用数量, 锁定数量, 已售数量, 状态])
    local skuStockValue = {}
    for value in string.gmatch(valueStrArr[i], "%d+") do
        table.insert(skuStockValue, value)
    end
    local totalSkuStockValue = {}
    for value in string.gmatch(totalValueStrArr[i], "%d+") do
        table.insert(totalSkuStockValue, value)
    end
    -- 执行redis的del指令，删除锁定记录（删除成功才进行更新sku库存）
    local param = params[i]
    local isDelete = redis.call('del', "mall4j_product:allot_order_sku_lock:"..param[1].."_"..param[2].."_"..param[3])
    if isDelete == 0 then return result end
    -- 将新的sku库存的key-value封装成数组（减少锁定）
    local lockNum = tonumber(param[4])
    local lock = tonumber(skuStockValue[2]) - lockNum
    table.insert(skuStockKV, "mall4j_product:sku_sock:"..param[3].."_"..param[2])
    table.insert(skuStockKV, skuStockValue[1].."_"..lock.."_"..skuStockValue[3].."_"..skuStockValue[4])
    lock = tonumber(totalSkuStockValue[2]) - lockNum
    table.insert(skuStockKV, "mall4j_product:sku_sock:"..param[3])
    table.insert(skuStockKV, totalSkuStockValue[1].."_"..lock.."_"..totalSkuStockValue[3].."_"..totalSkuStockValue[4])
    -- 拼接执行结果
    result = result..param[1].."_"..param[2].."_"..param[3].."_"..skuStockValue[1]..","
end

-- 执行redis的mset指令，更新库存数据
redis.call('mset', unpack(skuStockKV))

-- 返回执行结果
return result